#pragma once
#include <iostream>
#include <pthread.h>

class Mutex
{
public:
    Mutex()
    {
        int n = pthread_mutex_init(&_lock, nullptr);
        if (n != 0)
        {
            std::cout << "互斥锁初始化失败" << std::endl;
            return;
        }
        std::cout << "互斥锁初始化成功" << std::endl;
    }
    void lock()
    {
        int n = pthread_mutex_lock(&_lock);
        if (n != 0)
        {
            std::cout << "上锁失败" << std::endl;
            return;
        }
        std::cout << "上锁成功" << std::endl;
    }
    void unlock()
    {
        int n=pthread_mutex_unlock(&_lock);
        if (n != 0)
        {
            std::cout << "解锁失败" << std::endl;
            return;
        }
        std::cout << "解锁成功" << std::endl;
    }
    pthread_mutex_t*Get()
    {
        return &_lock;
    }
    ~Mutex()
    {
        int n = pthread_mutex_destroy(&_lock);
        if (n != 0)
        {
            std::cout << "互斥锁销毁失败" << std::endl;
            return;
        }
        std::cout << "互斥锁销毁成功" << std::endl;
    }

private:
    pthread_mutex_t _lock;
};

class LockGuard
{
public:
    LockGuard(Mutex *mutex)
        :_mutex(mutex)
    {
        _mutex->lock();
    }
    ~LockGuard()
    {
        _mutex->unlock();
    }
private:
    Mutex *_mutex;
};